<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        //多层对象或数组的深拷贝函数
        function deepCopy(obj1) {
            //精确判断传入数据 根据类型自动创建空数组或空对象
            var obj2 = Object.prototype.toString.call(obj1) === "[object Array]" ? [] : {};
            //for in 遍历数据 (有缺陷,会遍历原型)
            for (var key in obj1) {
                //判断是否是自身属性(弥补缺陷)
                if (obj1.hasOwnProperty(key)) {
                    //判断内层数据类型
                    if (typeof obj1[key] === "object") {
                        obj2[key] = deepCopy(obj1[key])
                    } else {
                        obj2[key] = obj1[key]
                    }
                }
            }
            return obj2;
        }


        var obj1 = {
            name: "张三",
            age: 20,
            hobby: {
                name1: "篮球",
                name2: "足球"
            }
        }

        var obj2 = deepCopy(obj1);
        obj2.hobby.name1 = "羽毛球";
         //修改obj2内层数据   obj2 改变了
         console.log(obj2);
         //obj1 没变化
        console.log(obj1);
       
    </script>
</body>

</html>